package com.yamaha.bikemarket;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class WantToSellEditFragment extends AMyActivity implements
		OnEditorActionListener, OnItemClickListener {

	private final static int TAKE_A_PHOTO = 50202;
	private final static int SELECT_PICTURE = 50230;
	private final static int REQUEST_CODE_CROP = 50240;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private MyAdapter mAdapter;
	private final List<Bitmap> list = new ArrayList<Bitmap>();

	private int userChooseImageIndex;

	final static int IMAGE_BUTTON = 0X1242;
	private ImageLoader imageLoader;

	private String temp;

	private MyState state = MyState.NONE;

	private enum MyState {
		PHOTO, NONE
	}

	private boolean isCreated = false;
	private final String TAG = "WantToSellEditFragment";

	public WantToSellEditFragment() {
		super(MenuType.NONE);
	}

	@Override
	public void onClick(View v) {
		if (onMenuClick(v)) {
			return;
		}

		switch (v.getId()) {
		case R.id.ws_brand: {
			handleBand();
		}
			break;
		case R.id.ws_model: {
			handleModel();
		}
			break;
		case R.id.ws_regyear: {
			handleRegYear();
		}
			break;
		case R.id.ws_color: {
			handleColor();
		}
			break;
		case R.id.ws_save: {
			handleSave();
		}
			break;
		case R.id.ws_delete: {
			handleDelete();
		}
			break;
		}
	}

	private void handleSave() {

		final Button brand = (Button) findViewById(R.id.ws_brand);
		final Button model = (Button) findViewById(R.id.ws_model);
		final Button regYear = (Button) findViewById(R.id.ws_regyear);
		final Button color = (Button) findViewById(R.id.ws_color);
		final EditText price = (EditText) findViewById(R.id.ws_price);
		final EditText phone = (EditText) findViewById(R.id.ws_phone);
		final EditText regNo = (EditText) findViewById(R.id.ws_regno);
		final EditText machNo = (EditText) findViewById(R.id.ws_machine_no);
		final EditText description = (EditText) findViewById(R.id.ws_description);

		// Check Image
		boolean hasImage = false;
		for (int i = 0; i <= 4 && !hasImage; i++) {
			final Bitmap bitmap = loadFile("" + i);
			if (null != bitmap) {
				hasImage = true;
			}
		}

		final String msg;
		if (brand.getTag() == null) {
			msg = "Brand requires a value.";
		} else if (model.getTag() == null) {
			msg = "Model requires a value.";
		} else if (color.getTag() == null) {
			msg = "Color requires a value.";
		} else if (price.getText().toString().trim().length() == 0) {
			msg = "Price requires a value.";
		} else if (!hasImage) {
			msg = "Please add at least one image before save.";
		} else {
			msg = "";
		}

		if (msg.length() > 0) {

			LogUtil.w("WantToSellEditFragment", "Save Validation Error : "
					+ msg);

			// Utils.showAlertDialog(this, "Error", msg);
			Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

		} else {

			Utils.showProgressDialog(this, "", "Saving...");

			final Button saveButton = (Button) findViewById(R.id.ws_save);
			saveButton.setEnabled(false);

			try {

				final JSONObject brandObj = (JSONObject) brand.getTag();
				final JSONObject modelObj = (JSONObject) model.getTag();
				final JSONObject colorObj = (JSONObject) color.getTag();
				final String regYearObj = (String) regYear.getTag();
				final String pmin = price.getText().toString();
				final String rn = regNo.getText().toString();
				final String mn = machNo.getText().toString();
				final String p = phone.getText().toString();
				final String d = description.getText().toString();

				final RequestParams params = new RequestParams();
				params.put("user_id", SCStaticFunc.getUserId(this));

				// For Edit
				if (temp != null && temp.length() > 0) {
					params.put("temp", temp);
				}

				if (brandObj != null) {
					params.put("brand_id", brandObj.getString("brand_id"));
				} else {
					params.put("brand_id", "");
				}
				if (modelObj != null) {
					params.put("model_id", modelObj.getString("model_id"));
				} else {
					params.put("model_id", "");
				}
				if (colorObj != null) {
					params.put("color_id", colorObj.getString("color_id"));
				} else {
					params.put("color_id", "");
				}
				if (pmin != null) {
					params.put("price", pmin);
				} else {
					params.put("price", "");
				}
				if (rn != null) {
					params.put("reg_no", rn);
				} else {
					params.put("reg_no", "");
				}
				if (regYearObj != null) {
					params.put("reg_year", regYearObj);
				} else {
					params.put("reg_year", "");
				}
				if (mn != null) {
					params.put("machine_no", mn);
				} else {
					params.put("machine_no", "");
				}
				if (p != null) {
					params.put("phone", p);
				} else {
					params.put("phone", "");
				}
				if (d != null) {
					params.put("description", d);
				} else {
					params.put("description", "");
				}

				LogUtil.i("WantToSellEditFragment",
						"Save Param : " + params.toString());

				final AsyncHttpClient client = new AsyncHttpClient();

				client.post(API.SAVE_WANT_TO_SELL, params,
						new MyAsyncHttpResponseHandler(API.SAVE_WANT_TO_SELL,
								this) {

							@Override
							public void onSuccess(final String res) {
								super.onSuccess(res);

								try {
									final JSONObject object = new JSONObject(
											res);

									SCStaticFunc.setData(
											WantToSellEditFragment.this,
											SCStaticFunc.YEAR,
											object.getJSONArray("year"));

									final boolean isSuccess = object
											.getBoolean("success");
									if (isSuccess) {
										Toast.makeText(
												WantToSellEditFragment.this,
												"Saved..", Toast.LENGTH_SHORT)
												.show();

										final String insertId = object
												.getString("message");
										handleSaveImage(insertId);

									} else {

										Utils.closeAllDialog();

										Toast.makeText(
												WantToSellEditFragment.this,
												object.getString("message"),
												Toast.LENGTH_SHORT).show();
										saveButton.setEnabled(true);
									}

								} catch (JSONException e) {
									Utils.closeAllDialog();

									LogUtil.e("WantToSellEditFragment",
											"Save Success : " + e.getMessage(),
											e);

									saveButton.setEnabled(true);
								}
							}
						});

			} catch (JSONException e) {
				LogUtil.e("WantToSellEditFragment",
						"handleSave : " + e.getMessage(), e);
			}
		}
	}

	private void handleSaveImage(final String insertId) {

		final List<Bitmap> lists = new ArrayList<Bitmap>();

		for (int i = 0; i <= 4; i++) {
			final Bitmap bitmap = loadFile("" + i);
			if (bitmap != null) {
				lists.add(bitmap);
			}
		}

		final RequestParams params = new RequestParams();
		params.put("user_id", SCStaticFunc.getUserId(this));
		params.put("id", insertId);
		int index = 0;
		for (int i = 0; i <= 4; i++) {
			try {
				final FileInputStream fileInputStream = openFileInput("" + i);

				params.put("picture_" + index, fileInputStream);
				index++;

			} catch (FileNotFoundException e) {
				LogUtil.w("WantToSellEditFragment", "File : " + i
						+ " not found.");
			}
		}

		final AsyncHttpClient client = new AsyncHttpClient();
		client.post(API.SAVE_WANT_TO_SELL_IMAGE, params,
				new MyAsyncHttpResponseHandler(API.SAVE_WANT_TO_SELL_IMAGE,
						this) {

					@Override
					public void onFinish() {
						super.onFinish();
						Utils.closeAllDialog();

						finish();
					}
				});

		final Button saveButton = (Button) findViewById(R.id.ws_save);
		saveButton.setEnabled(true);
	}

	private void handleBand() {

		final Button brandButton = (Button) findViewById(R.id.ws_brand);

		try {

			final List<String> data = new ArrayList<String>();

			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.BAND);

			for (int i = 0; i < array.length(); i++) {
				final JSONObject obj = array.getJSONObject(i);

				final String name = obj.getString("name");
				data.add(name);
			}

			showDialog(data, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					try {
						final JSONObject obj = (JSONObject) array.get(which);
						brandButton.setText(obj.getString("name"));
						brandButton.setTag(obj);
					} catch (JSONException e) {
						LogUtil.e("WantToBuyEditFragment",
								"handleBrand: " + e.getMessage(), e);
					}
				}

			});

		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleBrand: " + e.getMessage(), e);
		}
	}

	private void handleRegYear() {

		final Button btn = (Button) findViewById(R.id.ws_regyear);

		final List<String> data = new ArrayList<String>();
		try {
			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.YEAR);
			for (int i = 0; i < array.length(); i++) {
				data.add(array.getString(i));
			}
		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleRegYear : " + e.getMessage(), e);
		}

		showDialog(data, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				final String val = (2000 + which) + "";
				LogUtil.v("Reg Year", val);
				btn.setText(val);
				btn.setTag(val);
			}

		});

	}

	//
	private void handleModel() {

		final Button btn = (Button) findViewById(R.id.ws_model);

		try {

			final List<String> data = new ArrayList<String>();

			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.BAND);

			final List<JSONObject> mList = new ArrayList<JSONObject>();

			for (int i = 0; i < array.length(); i++) {
				final JSONObject obj = array.getJSONObject(i);

				final JSONArray model = obj.getJSONArray("model");
				for (int j = 0; j < model.length(); j++) {
					final JSONObject mObj = model.getJSONObject(j);

					mList.add(mObj);

					final String name = mObj.getString("name");
					data.add(name);
				}
			}

			showDialog(data, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					try {
						final JSONObject obj = mList.get(which);
						btn.setText(obj.getString("name"));
						btn.setTag(obj);
					} catch (JSONException e) {
						LogUtil.e("WantToBuyEditFragment",
								"handleModel : " + e.getMessage(), e);
					}

				}

			});

		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleModel : " + e.getMessage(), e);
		}
	}

	//
	private void handleColor() {

		final Button btn = (Button) findViewById(R.id.ws_color);

		try {

			final List<String> data = new ArrayList<String>();

			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.COLOR);

			for (int i = 0; i < array.length(); i++) {
				final JSONObject obj = array.getJSONObject(i);

				final String name = obj.getString("name");
				data.add(name);
			}

			showDialog(data, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					try {
						final JSONObject obj = (JSONObject) array.get(which);
						btn.setText(obj.getString("name"));
						btn.setTag(obj);
					} catch (JSONException e) {
						LogUtil.e("WantToBuyEditFragment",
								"handleColor : " + e.getMessage(), e);
					}

				}

			});

		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleColor : " + e.getMessage(), e);
		}
	}

	private void showDialog(final List<String> data,
			final DialogInterface.OnClickListener listener) {

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose item...");
		builder.setItems(data.toArray(new String[data.size()]), listener);
		builder.create().show();
	}

	@Override
	protected List<EditText> getEditTexts() {
		final ArrayList<EditText> editList = new ArrayList<EditText>();

		if (isCreated) {

		}

		return editList;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ws_edit_layout);

		LogUtil.v(TAG, "onCreate");

		temp = getIntent().getStringExtra("temp");

		state = MyState.NONE;

		if (temp == null) {
			final Button delButton = (Button) findViewById(R.id.ws_delete);
			delButton.setVisibility(View.GONE);
			delButton.setEnabled(false);
		} else {
			final Button delButton = (Button) findViewById(R.id.ws_delete);
			delButton.setVisibility(View.VISIBLE);
			delButton.setEnabled(true);
			delButton.setOnClickListener(this);
		}

		final DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory().cacheOnDisc().build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).defaultDisplayImageOptions(
				defaultOptions).build();
		if (null != imageLoader && imageLoader.isInited()) {
			imageLoader.destroy();
			imageLoader = null;
		}
		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			imageLoader.init(config);
		}

		// Default Value
		userChooseImageIndex = -1;

		if (null != savedInstanceState) {
			final String tempState = savedInstanceState.getString("state");
			if (tempState != null) {

				final MyState myState = MyState.valueOf(tempState);

				switch (myState) {
				case PHOTO: {
					userChooseImageIndex = savedInstanceState
							.getInt("photo_index");
				}
					break;
				case NONE: {

				}
					break;
				}
			}
		}

		final Button brand = (Button) findViewById(R.id.ws_brand);
		final Button model = (Button) findViewById(R.id.ws_model);
		final Button regYear = (Button) findViewById(R.id.ws_regyear);
		final Button color = (Button) findViewById(R.id.ws_color);
		final EditText price = (EditText) findViewById(R.id.ws_price);
		final EditText phone = (EditText) findViewById(R.id.ws_phone);
		final EditText regNo = (EditText) findViewById(R.id.ws_regno);
		final EditText machNo = (EditText) findViewById(R.id.ws_machine_no);
		final EditText description = (EditText) findViewById(R.id.ws_description);
		final Button saveButton = (Button) findViewById(R.id.ws_save);

		price.setOnEditorActionListener(this);
		phone.setOnEditorActionListener(this);
		regNo.setOnEditorActionListener(this);
		machNo.setOnEditorActionListener(this);
		description.setOnEditorActionListener(this);
		brand.setOnClickListener(this);
		model.setOnClickListener(this);
		regYear.setOnClickListener(this);
		color.setOnClickListener(this);
		saveButton.setOnClickListener(this);

		final List<String> url = new ArrayList<String>();

		if (null != savedInstanceState) {

			LogUtil.v(TAG, "Save Instance : " + savedInstanceState.toString());

			try {
				final String s = savedInstanceState.getString("brand");
				if (null != s) {
					final JSONObject object = new JSONObject(s);
					brand.setTag(object);
					brand.setText(object.getString("name"));
				}
			} catch (JSONException e) {
				LogUtil.w("WantToSellEditFragment", "onCreate: No Brand");
			}

			try {
				final String s = savedInstanceState.getString("model");
				if (null != s) {
					final JSONObject object = new JSONObject(s);
					model.setTag(object);
					model.setText(object.getString("name"));
				}
			} catch (JSONException e) {
				LogUtil.w("WantToSellEditFragment", "onCreate: No Modle");
			}

			{
				final String s = savedInstanceState.getString("regYear");
				if (null != s) {
					regYear.setTag(s);
					regYear.setText(s);
				}
			}

			try {
				final String s = savedInstanceState.getString("color");
				if (null != s) {
					final JSONObject object = new JSONObject(s);
					color.setTag(object);
					color.setText(object.getString("name"));
				}
			} catch (JSONException e) {
				LogUtil.w("WantToSellEditFragment", "onCreate: No Color");
			}
		} else {

			final String detail = getIntent().getStringExtra("detail");
			if (null != detail && temp != null) {

				try {
					final JSONObject item = new JSONObject(detail);
					price.setText(item.getString("price"));
					description.setText(item.getString("description"));
					regNo.setText(item.getString("reg_no"));
					machNo.setText(item.getString("machine_no"));
					phone.setText(item.getString("phone"));

					brand.setText(item.getString("brand_name"));
					JSONArray array = (JSONArray) SCStaticFunc.getData(this,
							SCStaticFunc.BAND);
					for (int i = 0; i < array.length(); i++) {
						final JSONObject a = array.getJSONObject(i);
						if (a.getInt("brand_id") == item.getInt("brand_id")) {
							brand.setTag(a);
							break;
						}
					}

					// Model
					model.setText(item.getString("model_name"));
					for (int i = 0; i < array.length(); i++) {
						final JSONObject a = array.getJSONObject(i);
						final JSONArray mm = a.getJSONArray("model");

						for (int j = 0; j < mm.length(); j++) {
							final JSONObject m = mm.getJSONObject(j);

							if (m.getInt("model_id") == item.getInt("model_id")) {
								model.setTag(m);
							}
						}
					}

					// Color
					array = (JSONArray) SCStaticFunc.getData(this,
							SCStaticFunc.COLOR);
					color.setText(item.getString("color_name"));
					for (int i = 0; i < array.length(); i++) {
						final JSONObject a = array.getJSONObject(i);
						if (a.getInt("color_id") == item.getInt("color_id")) {
							color.setTag(a);
							break;
						}
					}

					regYear.setText(item.getString("reg_year"));
					regYear.setTag(item.getString("reg_year"));

					final JSONArray ii = item.getJSONArray("pix");
					for (int i = 0; i < ii.length(); i++) {
						url.add(ii.getString(i));
					}

				} catch (JSONException e) {
					LogUtil.e("WantToSellEditFragment", "onCreate Edit Mode: "
							+ e.getMessage(), e);
				}

			}

		}

		mAdapter = new MyAdapter(url.toArray(new String[url.size()]));

		final Gallery gallery = (Gallery) findViewById(R.id.ws_image);
		gallery.setAdapter(mAdapter);
		gallery.setOnItemClickListener(this);

		setListenerForMenu();

		isCreated = true;
	}

	private Bitmap loadFile(final String fileName) {

		try {
			FileInputStream fileInputStream = openFileInput(fileName);
			final Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);

			return bitmap;
		} catch (FileNotFoundException e) {
			LogUtil.w("WantToSellEditFragment", "Load File : " + e.getMessage()
					+ " FileNotFoundException");
		}

		return null;
	}

	private boolean saveFile(final String fileName, final Bitmap bitmap) {

		LogUtil.i("WantToSellEditFragment", "Save File : " + fileName);

		try {
			final FileOutputStream fileOutputStream = openFileOutput(fileName,
					Context.MODE_PRIVATE);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 95, fileOutputStream);

			return true;
		} catch (IOException e) {
			LogUtil.e("WantToSellEditFragment",
					"Save File : " + e.getMessage(), e);
		}

		return false;
	}

	private void deleteMyFile() {

		for (int i = 0; i <= 4; i++) {

			final String fileName = "" + i;
			LogUtil.i("WantToSellEditFragment", "Delete File : " + fileName);
			deleteFile("" + i);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		LogUtil.v(TAG, "onSaveInstanceState");

		outState.putString("state", state.name());

		final Button brand = (Button) findViewById(R.id.ws_brand);
		final Button model = (Button) findViewById(R.id.ws_model);
		final Button regYear = (Button) findViewById(R.id.ws_regyear);
		final Button color = (Button) findViewById(R.id.ws_color);

		if (null != brand.getTag()) {
			final JSONObject object = (JSONObject) brand.getTag();
			outState.putString("brand", object.toString());
			LogUtil.v(TAG, "onSaveInstanceState : Save Brand : " + object);
		}

		if (null != model.getTag()) {
			final JSONObject object = (JSONObject) model.getTag();
			outState.putString("model", object.toString());
			LogUtil.v(TAG, "onSaveInstanceState : Save model : " + object);
		}

		if (null != regYear.getTag()) {
			final String object = (String) regYear.getTag();
			outState.putString("regYear", object);
			LogUtil.v(TAG, "onSaveInstanceState : Save Reg year : " + object);
		}

		if (null != color.getTag()) {
			final JSONObject object = (JSONObject) color.getTag();
			outState.putString("color", object.toString());
			LogUtil.v(TAG, "onSaveInstanceState : Save Color : " + object);
		}

		switch (state) {
		case PHOTO: {
			outState.putInt("photo_index", userChooseImageIndex);

		}
			break;
		case NONE: {

		}
			break;

		}

		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		LogUtil.v(TAG, "onRestoreInstanceState");
		final Button brand = (Button) findViewById(R.id.ws_brand);

		if (null != savedInstanceState) {
			try {
				final String s = savedInstanceState.getString("brand");
				if (null != s) {
					final JSONObject object = new JSONObject(s);
					brand.setTag(object);
					brand.setText(object.getString("brand_name"));
				}
			} catch (JSONException e) {
				LogUtil.w("WantToSellEditFragment", "onCreate: No Brand");
			}
		}
	}

	private class ItemHolder {
		ImageView imageView;
	}

	private class MyAdapter extends BaseAdapter {

		private final String[] url;

		public MyAdapter(final String[] url) {
			this.url = url;
		}

		@Override
		public int getCount() {
			return 5;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup container) {

			final ItemHolder holder;
			if (convertView == null) {
				holder = new ItemHolder();

				holder.imageView = new ImageView(WantToSellEditFragment.this);

				convertView = holder.imageView;
				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			holder.imageView
					.setLayoutParams(new Gallery.LayoutParams(500, 365));
			holder.imageView.setId(IMAGE_BUTTON);
			holder.imageView.setTag(position);
			holder.imageView.setScaleType(ScaleType.MATRIX);
			// holder.imageView.setPadding(25, 5, 25, 5);
			holder.imageView.setImageResource(R.drawable.pix_add);

			final Bitmap bitmap = loadFile("" + position);
			if (null != bitmap) {

				LogUtil.i("WantToSellEditFragment", "User Image Index : "
						+ position + " from Bitmap.");
				holder.imageView.setImageBitmap(bitmap);
			} else {
				LogUtil.i("WantToSellEditFragment", "User Image Index : "
						+ position + " from URL.");
				if (position < url.length) {
					LogUtil.v("Loaded Image From URL", url[position]);
					imageLoader.displayImage(url[position], holder.imageView,
							new ImageLoadingListener() {

								@Override
								public void onLoadingStarted(String imageUri,
										View view) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onLoadingFailed(String imageUri,
										View view, FailReason failReason) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onLoadingComplete(String imageUri,
										View view, Bitmap loadedImage) {

									saveFile("" + position, loadedImage);
								}

								@Override
								public void onLoadingCancelled(String imageUri,
										View view) {
									// TODO Auto-generated method stub

								}
							});
				} else {
					holder.imageView.setImageResource(R.drawable.pix_add);
				}
			}

			return convertView;
		}
	}

	//
	private void handleDelete() {

		final RequestParams params = new RequestParams();
		params.put("temp", temp);

		Utils.showProgressDialog(this, "", "Deleting...");

		final AsyncHttpClient client = new AsyncHttpClient();
		client.post(API.DELETE_WANT_TO_SELL, params,
				new MyAsyncHttpResponseHandler(API.DELETE_WANT_TO_SELL, this) {

					@Override
					public void onSuccess(String r) {
						super.onSuccess(r);

						try {
							final JSONObject obj = new JSONObject(r);

							Utils.closeAllDialog();
							Toast.makeText(WantToSellEditFragment.this,
									"Deleted...", Toast.LENGTH_SHORT).show();

							finish();

						} catch (JSONException e) {
							LogUtil.e("WantToSEllEditFragment",
									"onDelete Success : " + e.getMessage(), e);
						}
					}

					@Override
					public void onFinish() {
						super.onFinish();

						Utils.closeAllDialog();
					}

				});
	}

	@Override
	public boolean onEditorAction(TextView edittext, int keyCode, KeyEvent event) {
		if ((keyCode == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
				|| (keyCode == EditorInfo.IME_ACTION_DONE)) {
			hideInputText();
			return true;
		}
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position,
			long id) {
		final ImageView imageButton = (ImageView) v;
		final int index = (Integer) imageButton.getTag();

		final String[] options = { "Camera", "Picture Library" };
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose...");
		builder.setItems(options, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, int which) {
				switch (which) {
				case 0: {
					handleCamera(index);
				}
					break;
				case 1: {
					handleChooseImageFromLibrary(index);
				}
					break;
				}
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private void handleChooseImageFromLibrary(final int index) {
		LogUtil.i("WantToSEllEditFragment", "User chooose image index : "
				+ index);

		userChooseImageIndex = index;
		state = MyState.PHOTO;

		if (isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE)) {
			final Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("image/*");
			startActivityForResult(photoPickerIntent, SELECT_PICTURE);
		} else {
			LogUtil.w("WantToSellEditFragment", "User has NOT Gallery.");
		}
	}

	private void handleCamera(final int index) {

		if (isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE)) {

			LogUtil.i("WantToSEllEditFragment", "User chooose image index : "
					+ index);

			userChooseImageIndex = index;
			state = MyState.PHOTO;

			// final Button brand = (Button) findViewById(R.id.ws_brand);
			// final Button model = (Button) findViewById(R.id.ws_model);
			// final Button regYear = (Button) findViewById(R.id.ws_regyear);
			// final Button color = (Button) findViewById(R.id.ws_color);
			//
			// if (null != brand.getTag()) {
			// final JSONObject object = (JSONObject) brand.getTag();
			// SCStaticFunc.setData(this, "BrandButton", object);
			// }
			//
			// if (null != model.getTag()) {
			// final JSONObject object = (JSONObject) model.getTag();
			// SCStaticFunc.setData(this, "ModelButton", object);
			// }
			//
			// if (null != regYear.getTag()) {
			// final String object = (String) regYear.getTag();
			// SCStaticFunc.setData(this, "RegyearButton", object);
			// }
			//
			// if (null != color.getTag()) {
			// final JSONObject object = (JSONObject) color.getTag();
			// SCStaticFunc.setData(this, "ColorButton", object);
			// }

			dispatchTakePictureIntent(TAKE_A_PHOTO);

		} else {
			LogUtil.w("WantToSellEditFragment", "User has NOT Camera.");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == TAKE_A_PHOTO) {
			handleSmallCameraPhoto(data);
		} else if (requestCode == SELECT_PICTURE) {
			handleAfterChooseImageFromGallery(data);
		} else if (requestCode == REQUEST_CODE_CROP) {
			handleAfterCrop(data);
		}

	}

	private void handleAfterChooseImageFromGallery(final Intent data) {
		try {
			final Uri selectedImage = data.getData();
			InputStream imageStream = getContentResolver().openInputStream(
					selectedImage);
			final Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

			final Options options = new Options();
			options.inSampleSize = 2;
			if (null != bitmap) {
				int w = (bitmap.getWidth() * 50) / 100;
				int h = (bitmap.getHeight() * 50) / 100;
				final Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap,
						w, h, true);

				// final Uri uri = Uri.fromFile(file);
				// handleCrop(uri);
				if (resizedbitmap != null) {
					saveFile("" + userChooseImageIndex, resizedbitmap);

					mAdapter.notifyDataSetChanged();
				} else {
					Toast.makeText(this,
							"Cannot save picture, Please try again.",
							Toast.LENGTH_SHORT).show();
				}
			}

		} catch (FileNotFoundException e) {
			LogUtil.e(TAG,
					"handleAfterChooseImageFromGallery : " + e.getMessage(), e);
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	private void dispatchTakePictureIntent(int actionCode) {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(getTempFile(this)));
		startActivityForResult(takePictureIntent, actionCode);
	}

	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	private File getTempFile(Context context) {
		final File path = new File(Environment.getExternalStorageDirectory(),
				context.getPackageName());
		if (!path.exists()) {
			path.mkdir();
		}
		return new File(path, "image.tmp");
	}

	private void handleSmallCameraPhoto(Intent intent) {
		final File file = getTempFile(this);

		LogUtil.i("WantToSellEditFragment", "Back from Camera with Index : "
				+ userChooseImageIndex);

		final Options options = new Options();
		options.inSampleSize = 2;
		final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),
				options);
		if (null != bitmap) {
			int w = (bitmap.getWidth() * 50) / 100;
			int h = (bitmap.getHeight() * 50) / 100;
			final Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap, w,
					h, true);

			// final Uri uri = Uri.fromFile(file);
			// handleCrop(uri);
			if (resizedbitmap != null) {
				saveFile("" + userChooseImageIndex, resizedbitmap);

				mAdapter.notifyDataSetChanged();
			} else {
				Toast.makeText(this, "Cannot save picture, Please try again.",
						Toast.LENGTH_SHORT).show();
			}
		}

		// final Button brand = (Button) findViewById(R.id.ws_brand);
		// final Button model = (Button) findViewById(R.id.ws_model);
		// final Button regYear = (Button) findViewById(R.id.ws_regyear);
		// final Button color = (Button) findViewById(R.id.ws_color);
		//
		// try {
		//
		// final JSONObject object = (JSONObject) SCStaticFunc.getData(this,
		// "BrandButton");
		// if (null != object) {
		// brand.setTag(object);
		// brand.setText(object.getString("name"));
		// LogUtil.v(
		// "WantToSellEditFragment",
		// "Set Brand : From HandlSmallImage :"
		// + object.getString("name"));
		// } else {
		// LogUtil.w("WantToSellEditFragment",
		// "handleSmall Image : Brand is nothing.");
		// }
		// } catch (JSONException e) {
		// LogUtil.w("WantToSellEditFragment", "handleSmallImage: No Brand");
		// }
		//
		// try {
		//
		// final JSONObject object = (JSONObject) SCStaticFunc.getData(this,
		// "ModelButton");
		// if (null != object) {
		// model.setTag(object);
		// model.setText(object.getString("name"));
		// } else {
		// LogUtil.w("WantToSellEditFragment",
		// "handleSmall Image : Model is nothing.");
		// }
		// } catch (JSONException e) {
		// LogUtil.w("WantToSellEditFragment", "handleSmallImage: No Model");
		// }
		//
		// try {
		//
		// final String object = (String) SCStaticFunc.getData(this,
		// "RegyearButton");
		// if (null != object) {
		// regYear.setTag(object);
		// regYear.setText(object);
		// } else {
		// LogUtil.w("WantToSellEditFragment",
		// "handleSmall Image : Reg Year is nothing.");
		// }
		// } catch (JSONException e) {
		// LogUtil.w("WantToSellEditFragment", "handleSmallImage: No Reg year");
		// }
		//
		// try {
		//
		// final JSONObject object = (JSONObject) SCStaticFunc.getData(this,
		// "ColorButton");
		// if (null != object) {
		// color.setTag(object);
		// color.setText(object.getString("name"));
		// } else {
		// LogUtil.w("WantToSellEditFragment",
		// "handleSmall Image : Color is nothing.");
		// }
		// } catch (JSONException e) {
		// LogUtil.w("WantToSellEditFragment", "handleSmallImage: No Color");
		// }

	}

	private void handleCrop(final Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setData(uri);
		intent.putExtra("outputX", 96);
		intent.putExtra("outputY", 96);
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_CROP);
	}

	@Override
	public void onBackPressed() {
		final RelativeLayout menuPanel = (RelativeLayout) findViewById(R.id.menu_panel);
		final RelativeLayout headerPanel = (RelativeLayout) findViewById(R.id.header_panel);
		final ImageButton button = (ImageButton) headerPanel
				.findViewById(R.id.menu_logo);

		if (menuPanel.getVisibility() == View.VISIBLE) {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);
			return;
		}

		deleteMyFile();

		super.onBackPressed();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// Clear All Image
		// deleteMyFile();

	}

	private void handleAfterCrop(final Intent data) {

	}
}
